package com.java110.assets.bmo.machine.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.assets.bmo.machine.IGetMachineBMO;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.client.RestTemplate;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.core.factory.RestTemplateFactory;
import com.java110.dto.machineStaffShow.MachineStaffShowDto;
import com.java110.po.machine.MachinePo;
import com.java110.utils.cache.CommonCache;
import com.java110.utils.cache.MappingCache;
import com.java110.utils.constant.MallConstant;
import com.java110.utils.constant.MappingConstant;
import com.java110.utils.util.CacheUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.java110.core.context.DataFlowContext;
import com.java110.intf.assets.IMachineInnerServiceSMO;
import com.java110.dto.machine.MachineDto;
import com.java110.utils.constant.BusinessTypeConstant;
import com.java110.utils.constant.CommonConstant;
import com.java110.utils.util.Assert;
import org.springframework.http.HttpStatus;
import com.java110.utils.util.BeanConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("getMachineBMOImpl")
public class GetMachineBMOImpl implements IGetMachineBMO {

    @Autowired
    private IMachineInnerServiceSMO machineInnerServiceSMOImpl;
    @Autowired
    private RestTemplate outRestTemplate;

    /**
     * @param machineDto
     * @return 订单服务能够接受的报文
     */
    public ResponseEntity<String> get(MachineDto machineDto) {


        int count = machineInnerServiceSMOImpl.queryMachinesCount( machineDto );

        List<MachineDto> machineDtos = null;
        if (count > 0) {
            machineDtos = machineInnerServiceSMOImpl.queryMachines( machineDto );
            reshWebSocketUrl(machineDtos);
        } else {
            machineDtos = new ArrayList<>();
        }

        ResultVo resultVo = new ResultVo( (int) Math.ceil( (double) count / (double) machineDto.getRow() ), count, machineDtos );

        ResponseEntity<String> responseEntity = new ResponseEntity<String>( resultVo.toString(), HttpStatus.OK );

        return responseEntity;
    }
    private void reshWebSocketUrl(List<MachineDto> machineDtos) {
        if (machineDtos == null || machineDtos.size() < 1) {
            return;
        }
        for (MachineDto machineDto : machineDtos) {
            machineDto.setWebsocketUrl( MappingCache.getValue( MappingConstant.KEY_DOMAIN_COMMON, MappingConstant.WEB_SOCKET_URL ) );
        }
    }
    /**
     * @param machineDto
     * @return 订单服务能够接受的报文
     */
    public ResponseEntity<String> checkMachine(MachineDto machineDto) {


        int count = machineInnerServiceSMOImpl.queryMachinesCount( machineDto );

        List<MachineDto> machineDtos = null;
        if (count > 0) {
            machineDtos = machineInnerServiceSMOImpl.queryMachines( machineDto );
        } else {
            machineDtos = new ArrayList<>();
        }
        JSONObject reqJson = new JSONObject();
        reqJson.put( "action", MachineDto.SIP_QUERY_SESSION );
        reqJson.put( "id", machineDtos.get( 0 ).getMachineCode() );
        ResponseEntity<String> responseEntity = RestTemplateFactory.restOutSipTemplate( reqJson, outRestTemplate, MallConstant.SIP_ACTION, HttpMethod.GET );
        if (responseEntity != null) {
            if (responseEntity.getStatusCode() != HttpStatus.OK) {
                throw new IllegalArgumentException( responseEntity.getBody() );
            }
        }
        JSONArray clients = null;
        JSONObject jsonBody = JSONObject.parseObject( responseEntity.getBody() );
        clients = JSONObject.parseArray( CommonCache.getValue( machineDto.getMachineId() ) );
        if (clients == null || clients.size() < 1) {
            clients = new JSONArray();
        }
        clients.add( machineDto.getClientId() + machineDtos.get( 0 ).getMachineCode() + machineDtos.get( 0 ).getMachineVersion() );
        CommonCache.setValue( machineDto.getMachineId(), clients.toJSONString() );
        JSONObject outJson = new JSONObject();
        if ("0".equals( jsonBody.getString( "code" ) )) {
            JSONObject data = jsonBody.getJSONObject( "data" );
            JSONArray session = data.getJSONArray( "sessions" );
            JSONArray devices = session.getJSONObject( 0 ).getJSONArray( "devices" );
            if (!"InviteOk".equals( devices.getJSONObject( 0 ).getString( "invite_status" ) )) {
                JSONObject reqInviteJson = new JSONObject();
                reqInviteJson.put( "action", MachineDto.SIP_INVITE );
                reqInviteJson.put( "id", machineDtos.get( 0 ).getMachineCode() );
                reqInviteJson.put( "chid", machineDtos.get( 0 ).getMachineVersion() );
                ResponseEntity<String> responseInviteEntity = RestTemplateFactory.restOutSipTemplate( reqInviteJson, outRestTemplate, MallConstant.SIP_ACTION, HttpMethod.GET );
                if (responseInviteEntity != null) {
                    if (responseInviteEntity.getStatusCode() != HttpStatus.OK) {
                        throw new IllegalArgumentException( responseInviteEntity.getBody() );
                    }
                }
            }
            outJson.put( "code","0" );
            outJson.put( "msg",machineDtos.get( 0 ).getMachineName()+"摄像头推流正常" );
        }else {
            outJson.put( "code","1" );
            outJson.put( "msg",machineDtos.get( 0 ).getMachineName()+"摄像头不在线" );
        }
        outJson.put( "url", MallConstant.getVideoSipUrl( machineDtos.get( 0 ).getMachineCode() + "@" + machineDtos.get( 0 ).getMachineVersion() ) );
        outJson.put( "machineId", machineDtos.get( 0 ).getMachineId() );
        responseEntity = new ResponseEntity<String>( outJson.toString(), HttpStatus.OK );

        return responseEntity;
    }

    /**
     * @param
     * @return 订单服务能够接受的报文
     */
    public ResponseEntity<String> outMachine(JSONObject reqJson) {

        JSONArray machines = reqJson.getJSONArray( "machines" );

        for (int machinesIndex = 0; machinesIndex < machines.size(); machinesIndex++) {
            MachinePo machinePo = BeanConvertUtil.covertBean( machines.get( machinesIndex ), MachinePo.class );
            JSONArray clients = JSONObject.parseArray( CommonCache.getValue( machinePo.getMachineId() ) );
            if (clients == null || clients.size() < 1) {
                JSONObject reqJsonBye = new JSONObject();
                reqJsonBye.put( "action", MachineDto.SIP_BYE );
                reqJsonBye.put( "id", machinePo.getMachineCode() );
                ResponseEntity<String> responseByeEntity = RestTemplateFactory.restOutSipTemplate( reqJsonBye, outRestTemplate, MallConstant.SIP_ACTION, HttpMethod.GET );
                if (responseByeEntity != null) {
                    if (responseByeEntity.getStatusCode() != HttpStatus.OK) {
                        throw new IllegalArgumentException( responseByeEntity.getBody() );
                    }
                }

            } else {
                for (int clientsIndex = 0; clientsIndex < clients.size(); clientsIndex++) {
                    String value = reqJson.getString( "clientId" ) + machinePo.getMachineCode() + machinePo.getMachineVersion();
                    if(value.equals( clients.getString( clientsIndex ) )){
                        clients.remove( clientsIndex );
                    }
                }
                CommonCache.setValue( machinePo.getMachineId(), clients.toJSONString() );
            }


        }

        return ResultVo.createResponseEntity( ResultVo.CODE_OK, "处理成功" );

    }
    /**
     * @param
     * @return 订单服务能够接受的报文
     */
    public ResponseEntity<String> clearMachine() {

        MachineDto machineDto = new MachineDto();
        int count = machineInnerServiceSMOImpl.queryMachinesCount( machineDto );

        List<MachineDto> machineDtos = null;
        if (count > 0) {
            machineDtos = machineInnerServiceSMOImpl.queryMachines( machineDto );
        } else {
            machineDtos = new ArrayList<>();
        }
        for(MachineDto machines: machineDtos){
            CommonCache.removeValue( machines.getMachineId() );
            JSONObject reqJsonBye = new JSONObject();
            reqJsonBye.put( "action", MachineDto.SIP_BYE );
            reqJsonBye.put( "id", machines.getMachineCode() );
            ResponseEntity<String> responseByeEntity = RestTemplateFactory.restOutSipTemplate( reqJsonBye, outRestTemplate, MallConstant.SIP_ACTION, HttpMethod.GET );
            if (responseByeEntity != null) {
                if (responseByeEntity.getStatusCode() != HttpStatus.OK) {
                    throw new IllegalArgumentException( responseByeEntity.getBody() );
                }
            }
        }

        return ResultVo.createResponseEntity( ResultVo.CODE_OK, "清理成功" );

    }

}
